<?php

namespace App\Imports;

use App\Classify;
use App\Enterprise;
use App\Merchant;
use App\MerchantMedicine;
use App\SystemMedicine;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Row;

class ExcelCheck implements OnEachRow,WithHeadingRow
{
    protected $allowMerchantIdArr   = [];
    protected $storeIdCache           = [];
    protected $classifyCache        = [];
    protected $unknownRow           = [];
    protected $addFirstClassify     = [];
    protected $addSecondClassify    = [];
    protected $addMedicineNum       = 0;
    protected $changeMedicineNum       = 0;
    protected $i                    = 1;
    protected $errorMessage         = [];
    protected $enterprise_id        = 0;
    protected $merchantMedicineUpcTemp = [];
    protected $systemMedicineUpcTemp = [];
    protected $noneSystemMedicine = [];
    protected $standardSystemMedicineNum = 0;
    protected $defaultMerchantId    = 0;
    protected $total_num            = 0;
    public function __construct($enterprise_id,$defaultMerchantId = 0)
    {
        $this->allowMerchantIdArr       = Enterprise::getEnterpriseMerchantIds($enterprise_id);
        \Log::notice('$this->allowMerchantIdArr:'.json_encode($this->allowMerchantIdArr));
        $this->enterprise_id            = $enterprise_id;
        $this->systemMedicineUpcTemp    = SystemMedicine::getUpcArray(0);
        $this->defaultMerchantId        = $defaultMerchantId;
        $this->storeIdCache[md5('default')]= $defaultMerchantId;
    }

    /**
     * @param Row $row
     * @return null
     */
    public function onRow(Row $row)
    {
        /** 校验 */
        $this->checkValue($row);
        $this->i = $this->i + 1;
    }

    public function getErrorMessage(){
        return $this->errorMessage;
    }
    public function getNotice(){
        return [
            'firstClassifyAdd'  =>$this->addFirstClassify,
            'secondClassifyAdd' =>$this->addSecondClassify,
            'firstClassifyAddNum'  =>count($this->addFirstClassify),
            'secondClassifyAddNum' =>count($this->addSecondClassify),
            'medicineAddNum'    =>$this->addMedicineNum,
            'medicineChangeNum' =>$this->changeMedicineNum,
            'noneSystemMedicineList' =>$this->noneSystemMedicine,
            'standardSystemMedicineNum' =>$this->standardSystemMedicineNum,
            'noneSystemMedicineNum' =>count($this->noneSystemMedicine),
        ];
    }

    public function getTotalNum(){
        return $this->total_num;
    }

    protected function checkValue($row){
        /** 取值 */
        $upc                =trim($row['bar_code']) ?? '';
        $store              =trim($row['store']) ?? '';
        $first_classify     =trim($row['first_classify']) ?? '';
        $second_classify    =trim($row['second_classify']) ?? '';
        $selling_price      =trim($row['selling_price']) ?? '';
        $stock              =trim($row['stock']) ?? 0;
        $is_shop            =trim($row['is_shop']) ?? 0;
        $sort               =trim($row['sort']) ?? 0;

        if (!$upc || $upc == 'upc码' || $upc == '商品条码'){
            $this->i++;
            return null;
        }

        if (!$store && !$this->defaultMerchantId){
            array_push($this->errorMessage,
                "第$this->i 行，excel表格中店铺名称未填写且未指定默认店铺,当前填写值：$store ，当前默认店铺id：$this->defaultMerchantId");
        }
        if (!$first_classify){
            array_push($this->errorMessage,"第$this->i 行，一级分类未填写，填写值：$first_classify");
        }
        if (!$second_classify){
            array_push($this->errorMessage,"第$this->i 行，二级分类未填写，填写值：$second_classify");
        }
        if (!$selling_price || !is_numeric($selling_price)){
            array_push($this->errorMessage,"第$this->i 行，销售价格未填写或填写的不是数字，填写值：$selling_price");
        }
        if (!is_numeric($stock)){
            array_push($this->errorMessage,"第$this->i 行，库存请填入数字，填写值：$stock");
        }
        if (!in_array($is_shop,[0,1])){
            array_push($this->errorMessage,"第$this->i 行，状态填了0/1之外的值，填写值：$is_shop");
        }
        if (!is_numeric($sort)){
            array_push($this->errorMessage,"第$this->i 行，排序请填入数字，或者不填，填写值：$sort");
        }

        if ($store){
            //门店缓存
            $storeKey = md5($store);
            if (!isset($this->storeIdCache[$storeKey])){
                //查库
                $thisMerchant = Merchant::whereEnterpriseId($this->enterprise_id)
                    ->whereName($store)
                    ->first();
                $this->storeIdCache[$storeKey] = $thisMerchant ? $thisMerchant->id : 0;
            }
            if (!in_array($this->storeIdCache[$storeKey],$this->allowMerchantIdArr)){
                array_push($this->errorMessage,"第$this->i 行，当前企业没有该门店,填写的门店名称：$store");
            }
        } else {
            $storeKey = md5('default');
        }

        if (!in_array($this->storeIdCache[$storeKey],$this->allowMerchantIdArr)){
            array_push($this->errorMessage,"第$this->i 行，指定的店铺不属于本企业，店铺id:".$this->storeIdCache[$storeKey]);
        }

        if ($first_classify){
            //一级分类缓存
            $classifyKey = md5($first_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($first_classify)
                    ->first();
                if (!$thisClassify){
                    if (!in_array($first_classify,$this->addFirstClassify)){
                        array_push($this->addFirstClassify,$first_classify);
                    }

                }
                $this->classifyCache[$classifyKey] = $thisClassify ? $thisClassify->id : 0;
            }
        }

        if ($second_classify){
            //二级分类缓存
            $classifyKey = md5($second_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($second_classify)
                    ->first();
                if (!$thisClassify){
                    if (!in_array($second_classify,$this->addFirstClassify)){
                        array_push($this->addSecondClassify,$second_classify);
                    }

                }
                $this->classifyCache[$classifyKey] = $thisClassify ? $thisClassify->id : 0;
            }
        }
        if ($upc){
            $this->total_num ++;
            //药品缓存
            if (!isset($this->merchantMedicineUpcTemp[$storeKey])){
                $this->merchantMedicineUpcTemp[$storeKey] = MerchantMedicine::whereMerchantId($this->storeIdCache[$storeKey])
                    ->orderByDesc('id')
//                    ->limit(8000)
                    ->pluck('upc')
                    ->toArray();
            }

            //TODO 是否已录入检测
            if (!in_array($upc,$this->merchantMedicineUpcTemp[$storeKey])){
              /*  $exist = MerchantMedicine::whereMerchantId($this->storeIdCache[$storeKey])
                    ->whereUpc($upc)
                    ->first();
                if (!$exist){
                    $this->addMedicineNum++;
                } else {
                    $this->changeMedicineNum++;
                }*/
                $this->addMedicineNum++;
            } else {
                $this->changeMedicineNum++;
            }

            //TODO 非标/数量检测
            if (!in_array($upc,$this->systemMedicineUpcTemp)){
                //未命中缓存
                /*$exist = SystemMedicine::whereStatus(1)
                    ->whereUpc($upc)
                    ->first();
                if (!$exist){
                    //TODO 非标统计
                    $temp = [
                        'row'=>$this->i,
                        'upc'=>$upc,
                    ];
                    array_push($this->noneSystemMedicine,$temp);
                } else {
                    //TODO 标准商品
                    $this->standardSystemMedicineNum++;
                }*/
                //TODO 非标统计
                $temp = [
                    'row'=>$this->i,
                    'upc'=>$upc,
                    'bar_code'=>$upc,
                    'store'=>$store,
                    'first_classify'=>$first_classify,
                    'second_classify'=>$second_classify,
                    'selling_prise'=>$selling_price,
                    'stock'=>$stock,
                    'is_shop'=>$is_shop,
                    'sort'=>$sort
                ];
                array_push($this->noneSystemMedicine,$temp);
            } else {
                //命中缓存
                //TODO 标准商品
                $this->standardSystemMedicineNum++;
            }


        }
    }
}
